from langchain_community.embeddings import DashScopeEmbeddings
#from langchain.vectorstores import  Milvus
from langchain_milvus import Milvus
from langchain_core.documents import  Document
from uuid import uuid4

#初始化模型
embeddings = DashScopeEmbeddings(
    model="text-embedding-v2",
    max_retries=3,
    dashscope_api_key="sk-4f1498f1c0314ba79ea2919bd7a02c4d"
)

document_1=Document(
    page_content="Langchain支持多种数据库集成，小弟课堂的AI大课.",
    metadata={"source":"xdclass.net/doc1"},
)
document_2=Document(
    page_content="Milvus擅长处理向搜索,小滴课堂的AI大课",
    metadata={"source":"xdclass.net/doc2"},
)
document_3=Document(
    page_content="我要去学小弟课堂的架构大课",
    metadata={"source":"xdclass.net/doc3"},
)
document_4=Document(
    page_content="今天天气不错，老王和老凡去按摩了",
    metadata={"source":"xdclass.net/doc4"},
)
# documents = [document_1, document_2, document_3, document_4]
# #创建向量数据库(from_documents会重复执行，又插入数据)
# vector_store = Milvus.from_documents(
#     documents=documents,
#     embedding=embeddings,
#     connection_args={"uri":"http://49.234.21.142:19530"},
#     collection_name = "mmr_test",
# )

#查询相关
vector_store = Milvus(
    embeddings,
    connection_args={"uri":"http://49.234.21.142:19530"},
    collection_name = "mmr_test",
)
print(vector_store)

#第一种查询方式（相似性搜索，会返回一样的数据）
# query = "如何进行数据库操作?"
# results= vector_store.similarity_search(query,k=3,expr='source=="xdclass.net/doc1"') #k返回3条,expr代表根据源进行过滤
# for result in results:
#     print(f"内容{result.page_content}元数据{result.metadata}")

#第二种查询方式(相似性搜索，会返回一样的数据)
# query = "如何进行数据库操作?"
# results = vector_store.similarity_search_with_score(query,k=3)
# for result in results:
#     print(f"内容{result[0].page_content}元数据{result[0].metadata}")
#     print(f"相似度{result[1]}")

#第三种方式(MMR搜索，不会返回一样的数据)
query = "如何进行数据库操作?"
results = vector_store.max_marginal_relevance_search(query,k=3,fetch_k=10,lambda_mult=0.4) #fetch_k 缓存10条,lambda_mult多样性参数(不会返回一模一样的结果)
for result in results:
    print(f"内容{result.page_content}元数据{result.metadata}")